﻿using System;
using System.Drawing;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media.Imaging;

namespace DACU.Tools
{
	class BitmapTools
	{
		public static BitmapSource BitmapToBitmapSource(Bitmap img)
		{
			var bmp = Imaging.CreateBitmapSourceFromHBitmap(img.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
			return bmp;
		}

		public static BitmapSource BitmapSourceFromUrl(Uri url)
		{
			var image = new BitmapImage();
			if (url != null)
			{
				try
				{
					image.BeginInit();
					image.CacheOption = BitmapCacheOption.OnLoad;
					image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
					image.UriSource = url;
					image.EndInit();
				}
				catch
				{
					image = null;
				}
			}
			return image;
		}

		public static BitmapSource BitmapSourceFromUrl(string url)
		{
			var image = new BitmapImage();
			if (!String.IsNullOrWhiteSpace(url))
			{
				try
				{
					image.BeginInit();
					image.CacheOption = BitmapCacheOption.OnLoad;
					image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
					image.UriSource = new Uri(url, UriKind.Absolute);
					image.EndInit();
				}
				catch
				{
					image = null;
				}
			}
			return image;
		}
	}
}
